package org.app.appjson.adapter;

import org.app.appjson.exception.AppJsonException;
import org.app.appjson.reader.JsonLexer;
import org.app.appjson.reader.JsonToken;
import org.app.appjson.reader.ReadHandler;
import org.app.appjson.writer.WriteHandler;

/**
 * Number类型适配器
 * @author lizhongsi
 * @version 1.0
 * @since 1.0
 */
public class NumberAdapter implements TypeAdapter {

    public static String read(ReadHandler handler) throws AppJsonException {
        JsonLexer lexer = handler.getLexer();
        if (lexer.peek().getType() == JsonToken.NULL) {
            lexer.next();
            return null;
        }
        if (lexer.peek().getType() == JsonToken.NUMBER) {
            return lexer.next().getValue();
        }
        throw new AppJsonException("NumberAdapter exception.");
    }

    public static void write(WriteHandler handler) throws AppJsonException {
        Object object = handler.getObject();
        if (!(object instanceof Number)) {
            throw new AppJsonException("Object is not Number type.");
        }
        handler.write(String.valueOf(object));
    }
}
